package cn.bctools.mail.controller;


import cn.bctools.mail.api.util.R;
import cn.bctools.mail.config.JwtUtil;
import cn.bctools.mail.entity.JamesUser;
import cn.bctools.mail.entity.dto.RegisterDTO;
import cn.bctools.mail.entity.enums.HashAlgorithmEnum;
import cn.bctools.mail.entity.vo.UserLoginVo;
import cn.bctools.mail.service.IJamesUserService;
import cn.hutool.crypto.digest.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@RestController
@AllArgsConstructor
@RequestMapping("/auth")
@Api(value = "auth", tags = "用户登录模块")
public class LoginController {


    private final static Lock lock = new ReentrantLock();

//    @Resource
//    IUserService userService;

    IJamesUserService jamesUserService;

    JwtUtil jwtUtil;

//    @Resource
//    IUserLoginInfoService userLoginInfoService;
//    @Resource
//    JwtComp jwtComp;
//
//    @Resource
//    ISeatUserService seatUserService;
//
//    @Resource
//    UserDealComp userDealComp;

    public static Map<String, String> verificationCodeMap = new HashMap<>();


    public static final String CURRENT_MODULE = "用户管理";

    @ApiOperation("用户注册")
    @PostMapping(value = "/register")
    @ResponseBody
    public R<Boolean> addUser(@Valid @RequestBody RegisterDTO registerDTO) {
        JamesUser jamesUser =  jamesUserService.queryByUserName(registerDTO.getUsername());
        if(jamesUser != null){
            return R.failed("邮箱已存在！");
        }
        JamesUser userBean = new JamesUser();
        userBean.setUserName(registerDTO.getUsername());
        userBean.setPasswordHashAlgorithm(HashAlgorithmEnum.MD5.getValue());
        userBean.setPassword(MD5.create().digestHex(registerDTO.getPassword()));
        userBean.setVersion(1l);
        Boolean aBoolean = jamesUserService.insert(userBean);
        return aBoolean ? R.ok(null, "邮箱注册成功！") : R.failed("邮箱注册失败！");
    }



    @ApiOperation("查看所有用户")
    @PostMapping(value = "/list")
    @ResponseBody
    public R<List<JamesUser>> list() {
        return R.ok(jamesUserService.all());
    }



//    @ApiOperation("平台用户登录平台用户登录认证后才能进入系统")
//    @GetMapping("seat/login")
//    @ResponseBody
//    public RestResult<UserLoginVo> seatUserLogin(
//            @Parameter(description = "平台token") String token) {
//        if (StringUtils.isEmpty(token)) {
//            return RestResult.fail().message("token 不能为空！");
//        }
//        SeatUser seatUser = seatUserService.getUserInfo(token);
//
//        if(seatUser == null){
//            return RestResult.fail().message("token过期失效,请重新登录！");
//        }
//
//        UserBean userBean = new UserBean();
//        userBean.setUsername(seatUser.getUsername());
//        userBean.setPassword(seatUser.getPassword());
//        lock.lock();
//        try {
//            if (!userDealComp.isUserNameExit(userBean)) {
//                RestResult registerResult = userService.registerUser(userBean);
//                if (!registerResult.getSuccess()) {
//                    return registerResult;
//                }
//            }
//        } finally {
//            lock.unlock();
//        }
//
//        RestResult<UserLoginVo> restResult = new RestResult<UserLoginVo>();
//        String salt = userService.getSaltByUsername(seatUser.getUsername());
//        String hashPassword = HashUtils.hashHex("MD5", seatUser.getPassword(), salt, 1024);
//        UserBean result = userService.selectUserByUsernameAndPassword(seatUser.getUsername(), hashPassword);
//        if (result == null) {
//            userService.updateUserPassword(seatUser.getUsername(), hashPassword);
//        }
//        Map<String, Object> param = new HashMap<>();
//        param.put("userId", result.getUserId());
//        try {
//            token = jwtComp.createJWT(param);
//        } catch (Exception e) {
//            log.info("登录失败：{}", e);
//            return RestResult.fail().message("创建token失败！");
//        }
//        UserBean sessionUserBean = userService.findUserInfoByUsername(seatUser.getUsername());
//        if (sessionUserBean.getAvailable() != null && sessionUserBean.getAvailable() == 0) {
//            return RestResult.fail().message("用户已被禁用");
//        }
//        UserLoginVo userLoginVo = new UserLoginVo();
//        BeanUtil.copyProperties(sessionUserBean, userLoginVo);
//        userLoginVo.setToken("Bearer " + token);
//        restResult.setData(userLoginVo);
//        restResult.setSuccess(true);
//        restResult.setCode(200001);
//        return restResult;
//    }


    @ApiOperation("用户登录用户登录认证后才能进入系统")
    @GetMapping("/login")
    @ResponseBody
    public R<UserLoginVo> userLogin(String username, String password) {
        UserLoginVo vo = new UserLoginVo();
        R<UserLoginVo> restResult = R.ok(vo);


        JamesUser jamesUser =  jamesUserService.queryByUserName(username);
        if(jamesUser == null){
            return R.failed("邮箱名"+ username +"不存在！");
        }

        String passwordMd5 = MD5.create().digestHex(password);
        if(!jamesUser.getPassword().equals(passwordMd5)){
            return R.failed("密码错误！");
        }

        Map<String, Object> map = new HashMap<>();
        // TODO 添加额外的东西
        // 生成token
        String jwt = jwtUtil.generateToken(jamesUser, map);
        vo.setUsername(jamesUser.getUserName());
        vo.setToken(jwt);
        return restResult;
    }

//    @ApiOperation("检查用户登录信息验证token的有效性")
//    @GetMapping("/checkuserlogininfo")
//    @ResponseBody
//    public RestResult<UserLoginVo> checkUserLoginInfo(@RequestHeader("token") String token) {
//        UserLoginVo userLoginVo = new UserLoginVo();
//        String userId = userService.getUserIdByToken(token);
//
//        if (StringUtils.isNotEmpty(userId)) {
//            LambdaQueryWrapper<UserLoginInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//            lambdaQueryWrapper.eq(UserLoginInfo::getUserId, userId);
//            lambdaQueryWrapper.likeRight(UserLoginInfo::getUserloginDate, DateUtil.getCurrentTime().substring(0, 10));
//            userLoginInfoService.remove(lambdaQueryWrapper);
//            UserLoginInfo userLoginInfo = new UserLoginInfo();
//            userLoginInfo.setUserId(userId);
//            userLoginInfo.setUserloginDate(DateUtil.getCurrentTime());
//            userLoginInfoService.save(userLoginInfo);
//            UserBean user = userService.getById(userId);
//            BeanUtil.copyProperties(user, userLoginVo);
//            if (StringUtils.isEmpty(user.getWxOpenId())) {
//                userLoginVo.setHasWxAuth(false);
//            } else {
//                userLoginVo.setHasWxAuth(true);
//            }
//            return RestResult.success().data(userLoginVo);
//
//        } else {
//            return RestResult.fail().message("用户暂未登录");
//        }
//
//    }



    @ApiOperation("获取邮件分组信息")
    @PostMapping("/token")
    public HashMap<String, Object> login() {
        HashMap<String, Object> res = new HashMap<>();
        res.put("access_token", "duVXxVS_VAfEIvd-LkCbJyMYunxtykZk4HqW1U01qQ0uwQ8zPM4x7u0zHqvSRm2pF-5tKcwCeXj3o8eHADnrxtPwhZ_qbj55kpYC8cTsOf5sKEYYKz4uE2PKBW57LYQl");
        res.put("expires_in", 3000000);
        String[] permissions = {
                "jvs_app_add",
                "jvs_app_import",
                "jvs_app",
                "jvs_app_unload",
                "jvs_teamwork_news",
                "jvs_teamwork_system_overview",
                "jvs-risk-databank",
                "chart-report-task-auth",
                "chart-report-task-template",
                "chart-report-task-dataintellect",
                "chart-report-task-datasource",
                "chart-report-task-service",
                "jvs-risk-dynamic-index",
                "add-file-action",
                "Test",
                "jvs-risk-function",
                "jvs-risk-variable-center",
                "jvs_automation_function",
                "jvs_automation_extend",
                "jvs_automation_encryption",
                "jvs_aps_material",
                "jvs_aps_material_add",
                "jvs_aps_material_edit",
                "jvs_aps_material_download_excel",
                "jvs_aps_material_import_excel",
                "jvs_aps_resource",
                "jvs_aps_resource_add",
                "jvs_aps_resource_edit",
                "jvs_aps_resource_download_excel",
                "jvs_aps_resource_import_excel",
                "jvs_aps_production_order",
                "jvs_aps_production_order_add",
                "jvs_aps_production_order_edit",
                "jvs_aps_production_order_download_excel",
                "jvs_aps_production_order_import_excel",
                "jvs_aps_incoming",
                "jvs_aps_incoming_add",
                "jvs_aps_incoming_edit",
                "jvs_aps_incoming_del",
                "jvs_aps_incoming_download_excel",
                "jvs_aps_incoming_import_excel",
                "jvs_aps_bom",
                "jvs_aps_bom_add",
                "jvs_aps_bom_edit",
                "jvs_aps_process",
                "jvs_aps_process_add",
                "jvs_aps_process_edit",
                "jvs_aps_process_route",
                "jvs_aps_process_route_edit",
                "jvs_aps_process_route_enable",
                "jvs_aps_process_route_disable",
                "jvs_aps_work_calendar",
                "jvs_aps_work_calendar_add",
                "jvs_aps_work_calendar_edit",
                "jvs_aps_work_calendar_del",
                "jvs_aps_work_mode_add",
                "jvs_aps_work_mode_edit",
                "jvs_aps_work_mode_del",
                "jvs_aps_strategy",
                "jvs_aps_strategy_add",
                "jvs_aps_strategy_edit",
                "jvs_aps_strategy_del",
                "jvs_aps_strategy_active",
                "jvs_aps_task",
                "jvs_aps_plan",
                "jvs_aps_plan_import_excel",
                "jvs_aps_plan_edit",
                "jvs_aps_global_config",
                "jvs_aps_global_config_edit",
                "jvs_aps_attribute",
                "jvs_aps_attribute_add",
                "jvs_aps_attribute_edit",
                "jvs_aps_estimated_order",
                "jvs_aps_estimated_order_add",
                "jvs_aps_estimated_order_edit",
                "jvs_aps_estimated_order_del",
                "jvs_aps_estimated_order_sort",
                "jvs_aps_estimated_order_download_excel",
                "jvs_aps_estimated_order_import_excel",
                "jvs_aps_estimated_order_config_save",
                "jvs_aps_estimated_order_delivery_time",
                "jvs_aps_auxiliary_resource",
                "jvs_aps_auxiliary_resource_add",
                "jvs_aps_auxiliary_resource_edit",
                "jvs_aps_auxiliary_resource_import_excel",
                "jvs_aps_auxiliary_resource_download_excel",
                "PERSONALIZED_CONFIGURATION_OF_DATA_INTELLIGENCE_WAREHOUSE",
                "PERSONALIZED_CONFIGURATION_IOT_PLATFORMS",
                "RULE_PERSONALIZATION_CONFIGURATION",
                "AUTOMATION_CONFIGURATION",
                "APS_CONFIGURATION",
                "ENTERPRISE_DOCUMENT_ENTERPRISE_CONFIGURATION",
                "PERSONALIZED_CONFIGURATION_OF_ENTERPRISE_PLANNING",
                "PERSONALIZED_CONFIGURATION_FOR_VIDEO_CONFERENCING",
                "PERSONALIZED_CONFIGURATION_OF_EMAIL_SERVICE",
                "BACKGROUND_PERSONALIZED_CONFIGURATION",
                "jvs_create_tenant",
                "jvs_platform",
                "ai"};
        res.put("permissions", permissions);
        res.put("refresh_token", "piWfiWzxzzlYR_uDGfXcBr0iyo5O0S0ytRhrek-JJgTegm-LtFoACk5UqArZCMGXtTxfy6T4nseQQla56XXMdN-xwiPTqCmwhIxIVaWlVIQReR-RgTdahrgZ9tSFwRuc");
        HashMap<String, String> tokenType = new HashMap<>();
        tokenType.put("value", "Bearer");
        res.put("tokenType", tokenType);
        res.put("userDto", "b43444018837fff1002d608fc623b70f258f3684b20da9e4205c59aae10b8d169e49a12abdaec8ad5bb35036aa8891f2d87b21144b5c9d45ed30c3746761ed47642fa77f94b9dc33b6862d034fcdf249d2792f225a9997beb8820222568a9507fa0af3923b3b676093e7680feb17c0d3615718967144f09a7781e16f8472caa06e6a4c35601cf2f20adb338ea4b985e9fb49d4fcbc2bfb7ff30564a772e4dc92ef9220571b93268d06ee32001f0cffc17322ae470bde11fa55b48f9a7cc1bcc4c892394c9b6b14be47bd4504740a5867bf026f6a1909c394f5d7fa5e917e4e33d947003699cf94048a87374bac4e14bf0902c5d602ddb2b1649d14860858ef68f4c1479238b91767a9692d355c8a58123f320efc16f60eadebe933e6c0960fa05848d23e72f2ea13278fce7e8b050ec1969c74b8f434595573f816766ebc13a8df9d4b8614551a4a4b4189f13659bcb480c83cf7bf94d15eb9d62e6c231e90428ade64e3713a225586c3a4d2120e6f9d2f71d37c5cfdf2f2b4fab0224cf7031cc32e9ad517e08a91a06b337925767dfb21aa73948f341d2b5a379bf88af3718c9bf45782e3471188e20a0e11e7df4e00f2ebb37d3cf033b609f6139c992e060b88bce684b6fee376a060ae1621d5d8ef086f2e01788133096aefe67aa22c2967e0979c9f3c52d97438bf3e9f9e6224dd8b0fbec7a5740333d57390dbf090b64204748caec4eae9f1bec91d61e4f29238ab949e94bb21527638fe6a5680554237e1f45f2caa8d7a47627f2c4311090520b5b6522069404140671599abc3b27f1975b7c6422b847119112645f5231ac09c15e5bc2a3c29ac34245708ad34bca133ec7cdbf0e86455fec59fb5044c1de7bd63bc463cbc779a8a85a32e7dca5cd1506675662308b70e96255d64ba698e043c80a59cea00acef013a31aefabf418621b87f1ba1fbc9e27ac472d77504a668a06422b5914f5baac11077e3fd341c1baa873a576b005b9bc856be83cd96c97794fa8324121a357b5f3cb14d3a866dd5da3da24a851da9b8fb18cfa87886982e10ee491edd993ca0286d55a8cec4de3f549f6750d19fd7e423a48b2530c7b64158b80f87fc129ecde43d1755e72b46b9319595050456a157e4a3d3bac9698a52376b96e094eb632d7039d1db78636b43499060da30bb61df07bf45c04a5dbae9b64aef3a15b5db2eae7e82be156e16a7f51045f05297bb9aedd3391ffb45264ca6e96c0a9b74d27acf79945b14b4788c4572db61d569d58a29783d547a4ff0a15398a76c83ce26f4d6554abe5f6af5500628ac8237217fba8b1124abee7f75295d602d6f5ed3722729d26b17520af30d27baba235901beee0b32dbb6bd80329ea1934028ad908d81acad5de1a42be33f46c8f0beed4a6120f6c7f347d46d4256fe4d1e1b42bf6f581bededc45bf9ff91908bae75ef6172f55fcfdf54d3d88595347b22550695163565d4f5da73874c214c6bb007ba76fc60b1303d9fd9d123120a91169a6458bae695f530fc309b85ccfc6440f2dfc719335f714fbddffd12aeeee9b8a27a93dc93f4227255ff9b05dae8c6364ca4351a71efee7cacf44b428dd064b028e5fe835afb2808b18e0382cf5d518e6bc8c28dc443a192851daa72fcb22c8ea128ca5de2ea4f403dbbd4351d29c3253985c6fc9f265380775f989be11d3de324a6e6bc05c8cbcfef6fec81ef4ad2d0da4c1fa049060fe6fc0b4ead0d8d48f76270e763800f3b488279be609451dd04cdcee1d54f8d391a1ff852f470b5e4f5ceced864430940259376ddeb71ac1a5f97751317c3b60b06adb3c3f326ddedc4bce685e79cdc590b6d202c1e4eb419cfb526e17a1ab9c9be8c78108d9eca5b86295b07a9d6320c97d59d0a41a3c5dfbb4238a949b98ea394d9016e5b17800b08bfe17e7572ecaa177144a8b6f53dd43a52de0a3e3603241889eaf52c630c3e6b117e28f69a08fa66f6e6a2913e1bcb51755014c482ab7b912ab087b900a6d665e113a68403863800534803e5c0c9968fd3af8a548010acbb4dc6cfdc6563a65d27d487e119179cd53d1476862e87e50edafe066591819fb04420e4b7848c51de8fe60047c73d689043aa60993a0b44149d30974ffde5bd12f04b67ad6001341e16d723293a52ebe4846e3bfb227e8b55c411c3251fd9d15a333ea3a3279004ce31a429272626dd212c360c481bc8f4fd2f36d537b2b31b0c83b320ef368d919814ee22a1b69d8c547d8ea071a7a6dba912565f8d03dd91078d3a0ce11cdfdac233abeffe78b8feefca11058063315b5c2bee6b86902256173bf135087667180c7b1376934d411c7323058a6bd07b4aad9fc683ab55f899486d2b9b64b93415f67a2ceaef6dcfafe2a5b4a18f38a99e9e4fc0e3e7b78227675fed57b1748b8baa638b5703df639728f88d14a51280fcabfb53c7eea8bb8a8854fa1a3882f05be523add3aadf4e2ce6f23f89048dffccf26a0aa5c179fe0363116de8be5e2fbc2e6f5f64880affc0197f31763326e40c356548610a1332e4c992adea68969b8cd3bc03607b3db9c0accb47994aaeb8c4faf7a5499b87554f567d888c15ee278f9bb80128b8aa5d9f01819562aa96b669a64a8f1b68222052cd3cfffb6dd5840db32ae0796e1a1ab11ab051499ab060afd59af7a7ce50efe3203ab6600e6affb57e34bf42bab4210cbd4b80a38fbecf1a8ae1185d3f383ecc9736605133490d1e97c7c7e02797e9c42a8ce523eb89a0dd8ec9025797f454fda35d5a824fee1defa6f8ce17d0565df54a4ab480f344fd999186e622413d312c1024094b05afb89a845d0c96b7e2a3929029769f4be466b3838380a9c3d9ca6398599aec30d4d312909875987cf44fb088f180dc932f81beead9b2c061c6b3b012cef39a1c1b50ed950997d713162f79b0790570618ed2ce531e51a9b74e21220f4096838bcdb9015da5e7505d739442beaf6da99e754200fd50a83f9cf966c14a5c01720d5dd0e7ce146e9c0b7e865fe323cd8fdac7225168690c130322fc77d52c3975a3f5ff313df20c29a624bd6ea786259e50a4a99093824e06daaf10b42170103e6ddcd7f35c0c89d4a36f5ff1b5494cd2504eb7");
        res.put("username", "testadmin");
        return res;
    }
}
